package com.kuhyygy.xml;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.util.Log;

import com.kuhyygy.bean.Person;

/**
 * Dom方式读取
 * 
 * @author KuhYygy
 * 
 */
public class DomXmlHandler {

	public static List<Person> readXml(InputStream ins) throws Exception {
		List<Person> list = new ArrayList<Person>();
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbFactory.newDocumentBuilder();
		Document doc = db.parse(ins);
		Element rootEl = doc.getDocumentElement();
		NodeList nodeList = rootEl.getElementsByTagName("pre:person");
		for (int i = 0; i < nodeList.getLength(); i++) {
			Log.i("tag", Short.toString(nodeList.item(i).getNodeType()));
			Element personNode = (Element)nodeList.item(i);
			Person p = new Person();
			p.setId(personNode.getAttribute("id"));
			
			NodeList subPerList = personNode.getChildNodes();
			if (subPerList.getLength() > 0) {
				for (int j = 0 ; j < subPerList.getLength(); j ++) {
					Node subEl = (Node) subPerList.item(j);
					
					if (subEl.getNodeType() == Node.ELEMENT_NODE) {
						String perAttr = subEl.getNodeName();
						
						/* Dom解释时要注意的地方 */
						String nodeVal = subEl.getFirstChild().getNodeValue();
						if ("name".equals(perAttr)) {
							p.setName(nodeVal);
						} else if ("age".equals(perAttr)) {
							p.setAge(Short.parseShort(nodeVal));
						}
					}
				}
			}
			list.add(p);
		}
		return list;
	}
}
